﻿package com.crl.module.media.player {
	import com.crl.module.media.events.SoundEvent;
	
	import flash.events.*;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundLoaderContext;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	
	public class MP3Player extends AbstractPlayer implements IPlayer {
		protected var sound:Sound;
		protected var channel:SoundChannel;
		protected var buffer:SoundLoaderContext;
		protected var request:URLRequest;
		
		public function MP3Player(){

		}
		override protected function init():void{
			this.sound=new Sound();
			this.sound.addEventListener(ProgressEvent.PROGRESS,loadProgressHandler);

			this.buffer=new SoundLoaderContext();
			this.buffer.bufferTime=5;
			
			request=new URLRequest();
		}

		public function load(path:String):void{
			this._currentPath=path;
			request.url=path;
			this.sound.load(request,this.buffer);
			this._playing=true;
		}
		private function onCompleteHander(event:Event):void{
			this.channel.stop();
			this._position=this.channel.position;
			this.completeHander(event);
		}
		
		
		public function play(position:int=0):void{
			this.position=position;
		}
		
		public function pause():void{
			if(this.isPlaying){
				this._position=this.channel.position;
				this.channel.stop();
			}else{
				this.position=this._position;
			}
			this._playing=!this.isPlaying;
		}
		public function stop():void{
			this.channel.stop();
		}
		public function replay():void{
			this.position=0;
		}
		
		public function get totalTime():Number{
			return this.sound.length;
		}
		
		public function set position(value:Number):void{
			if(this.channel){
				this.channel.removeEventListener(Event.SOUND_COMPLETE,onCompleteHander);
			}
			this.channel=this.sound.play(value);
			this.channel.addEventListener(Event.SOUND_COMPLETE,onCompleteHander);
			
			this.dispatchEvent(new SoundEvent(SoundEvent.POSITION_CHANGE));
		}
		
		public function get position():Number{
			return this.channel.position
		}
		
		public function get volume():Number{
			return this.channel.soundTransform.volume;
		}
		public function set volume(value:Number):void{
			var soundTransform:SoundTransform=this.channel.soundTransform;
			soundTransform.volume=value;
			this.channel.soundTransform=soundTransform;
			
			this.dispatchEvent(new SoundEvent(SoundEvent.VOLUME_CHANGE));
		}
		
		
		public function close():void{
			this.sound.close();
		}
		public function getSoundTransform():SoundTransform{
			return this.channel.soundTransform;
		}
		public function setSoundTransform(trans:SoundTransform):void{
			this.channel.soundTransform=trans;
		}
	}
	
}
